const clientFacade = require('../../app/facade/client.facade.js');
const _ = require('lodash');
const constValue = require('../utils/const.js');
const responseMsg = require('../utils/responseMsg.js');
var mongoose = require('mongoose');
var ClientModel = mongoose.model('Client');

var formidable = require('formidable');
const envConfig = require('../utils/config_development');
util = require('util');
var _f=require('../utils/file.js');

let uuid = require('node-uuid');
module.exports = {
    login: login,
    regist: regist
}

function login(req, res, next) {
    let body = req.body;
    let cname = body.cname;
    let cpwd = body.cpwd;
    
    if (_.isEmpty(cname) || _.isEmpty(cpwd)) {
        res.json(new responseMsg('500',constValue.NONE_MESSGAE,null));
        
    } else {
        ClientModel.findOne({'cname':cname,'cpwd':cpwd},function(err, doc){
            if(err) {
                var msg = new responseMsg('500',constValue.ERROR_MESSGAE,null);
                res.json(msg);
            }
            console.log(doc+"login!!!!!!!!!!!!!!!!!");
            res.json(doc);
        })
    }
}
function regist(req, res, next) {
    var form = new formidable.IncomingForm();

    _f.uploadSetting(form);
    form.parse(req, function (err, fields, files) {

        var client = fields;
        let uuid_v4 =  uuid.v4();
        console.log(uuid_v4+"uuid!!!!!!!");
        client.portrait = envConfig.upload.portrait+uuid_v4+".jpg";
        console.log(client+"client!!!!!!!!!!")
        clientFacade.addClient(client,function(err, docs) {
            
            if (err) {
                console.error(err);
            }
            // console.log(files);
            var fileName=uuid_v4+'.jpg';
            console.log(files.portrait.path);
            console.log(fileName);
      
            _f.rename(files.portrait.path,envConfig.upload.localImg+fileName);
            res.json(docs);
        })
    });
}

